package com.jwong.test;

import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation;
import io.fabric8.kubernetes.client.dsl.PodResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class CreatePod {

    private static final Logger logger = LoggerFactory.getLogger(CreatePod.class);

    public static void main(String[] args) {
        ConfigBuilder builder = new ConfigBuilder();
        Config config = builder.build();
        try (final KubernetesClient client = new DefaultKubernetesClient(config)) {
           String namespace = "default";
            CreatePod.class.getResourceAsStream("test-pod.yaml");
            List<HasMetadata> resources = client.load(CreatePod.class.getResourceAsStream("test-pod.yaml")).get();
            final HasMetadata resource = resources.get(0);
            if (resource instanceof Pod) {
                Pod pod = (Pod) resource;
                logger.info("Creating pod in namespace {}", namespace);
                NonNamespaceOperation<Pod, PodList, PodResource<Pod>> pods = client.pods().inNamespace(namespace);
                Pod result = pods.create(pod);
                logger.info("Created pod {}", result.getMetadata().getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
